package com.aj.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;

import com.aj.activity.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

public class PortraitLoaderUtil {
	public static void load(final Context context, ImageView view, String path,
			String url, final int startRID, final int faliedRID) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisc(true).build();
		ImageLoader imageLoader = ImageLoader.getInstance();

		if (FileHelper.isFileExist(path)) {
			Bitmap bmp = null;
			try {
				bmp = BitmapFactory.decodeStream(new FileInputStream(path));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			if (bmp == null)
				bmp = BitmapFactory.decodeResource(context.getResources(),
						faliedRID);
			bmp = ImageUtil.getRoundedCornerBitmap(bmp,
					UIUtil.dip2px(context, 100));
			view.setImageBitmap(bmp);
		} else if (TextUtil.isEmpty(url)) {
			Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
					faliedRID);
			bmp = ImageUtil.getRoundedCornerBitmap(bmp,
					UIUtil.dip2px(context, 100));
			view.setImageBitmap(bmp);
		} else {
			imageLoader.init(ImageLoaderConfiguration.createDefault(context));
			imageLoader.displayImage(url, view, options,
					new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							Bitmap bmp = BitmapFactory.decodeResource(
									context.getResources(), startRID);
							bmp = ImageUtil.getRoundedCornerBitmap(bmp,
									UIUtil.dip2px(context, 100));
							((ImageView) view).setImageBitmap(bmp);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								if (bmp != null) {
									bmp = ImageUtil.getRoundedCornerBitmap(bmp,
											UIUtil.dip2px(context, 100));
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							// TODO Auto-generated method stub
							if (loadedImage != null) {
								// loadedImage =
								// ImageUtil.ImageCrop(loadedImage);
								// loadedImage =
								// ImageUtil.zoomBitmap(loadedImage,
								// 200, 200);
								loadedImage = ImageUtil.getRoundedCornerBitmap(
										loadedImage,
										UIUtil.dip2px(context, 100));
								((ImageView) view).setImageBitmap(loadedImage);
							}
						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								if (bmp != null) {
									bmp = ImageUtil.getRoundedCornerBitmap(bmp,
											UIUtil.dip2px(context, 100));
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}
					});
		}
	}

	public static void loadSrc(final Context context, ImageView view,
			String path, String url, final int startRID, final int faliedRID,
			final int mWidth, final int mHeight) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.cacheOnDisk(true)
				// 设置下载的图片是否缓存在SD卡中
				.considerExifParams(true)
				// 是否考虑JPEG图像EXIF参数（旋转，翻转）
				.bitmapConfig(Bitmap.Config.RGB_565)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT)// 设置图片以如何的编码方式显示
				.cacheInMemory(true).cacheOnDisc(true).build();
		// File cacheDir = new File(MobileUtil.getFilePath() + "/.cache");
		ImageLoader imageLoader = ImageLoader.getInstance();
		// ImageLoaderConfiguration configuration = new
		// ImageLoaderConfiguration.Builder(
		// context)
		// .memoryCacheExtraOptions(480, 800)
		// // maxwidth,maxheight，即保存的每个缓存文件的最大长宽//default=devicescreendimensions
		// .threadPoolSize(3)
		// // 线程池内加载数量
		// .threadPriority(Thread.NORM_PRIORITY - 2)
		// .denyCacheImageMultipleSizesInMemory()
		// //
		// .memoryCache(newUsingFreqLimitedMemoryCache(14*1024*1024))//Youcanpassyourownmemorycacheimplementation/你可以通过自己的内存缓存实现
		// .memoryCache(new WeakMemoryCache())
		// .memoryCacheSize(2 * 1024 * 1024)
		// .diskCacheSize(80 * 1024 * 1024)
		// .discCacheFileNameGenerator(new Md5FileNameGenerator())
		// // 将保存的时候的URI名称用MD5加密
		// .tasksProcessingOrder(QueueProcessingType.LIFO)
		// .discCacheFileCount(100)
		// // 缓存的文件数量
		// .diskCache(new UnlimitedDiskCache(cacheDir))
		// // 自定义缓存路劲
		// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
		// .imageDownloader(
		// new BaseImageDownloader(context, 5 * 1000, 30 * 1000))//
		// connectTimeout(5s),readTimeout(30)超时时间
		// .writeDebugLogs()// Removeforreleaseapp
		// .build();// 开始构建
		// ImageLoader.getInstance().init(configuration);

		if (FileHelper.isFileExist(path)) {
			Bitmap bmp = null;
			try {
				Util util = new Util(context);
				bmp = util.getPathBitmap(Uri.fromFile(new File(path)), mWidth,
						mHeight);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			if (bmp == null)
				bmp = BitmapFactory.decodeResource(context.getResources(),
						faliedRID);
			view.setImageBitmap(bmp);
		} else if (TextUtil.isEmpty(url)) {
			Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
					faliedRID);
			view.setImageBitmap(bmp);
		} else {
			imageLoader.init(ImageLoaderConfiguration.createDefault(context));
			imageLoader.displayImage(url, view, options,
					new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							Bitmap bmp = BitmapFactory.decodeResource(
									context.getResources(), startRID);
							((ImageView) view).setImageBitmap(bmp);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								if (bmp != null) {
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							if (loadedImage != null) {
								// loadedImage =
								// ImageUtil.ImageCrop(loadedImage);
								// loadedImage =
								// ImageUtil.zoomBitmap(loadedImage,
								// 200, 200);
								((ImageView) view).setImageBitmap(loadedImage);
							}
						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								if (bmp != null) {
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}
					});
		}
	}

	public static void loadSrc(final Context context, ImageView view,
			String path, String url, final int startRID, final int faliedRID) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisc(true).build();
		File cacheDir = new File(MobileUtil.getFilePath() + "/.cache");
		ImageLoader imageLoader = ImageLoader.getInstance();
		ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
				context)
				.memoryCacheExtraOptions(480, 800)
				// maxwidth,maxheight，即保存的每个缓存文件的最大长宽//default=devicescreendimensions
				.threadPoolSize(3)
				// 线程池内加载数量
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				// .memoryCache(newUsingFreqLimitedMemoryCache(14*1024*1024))//Youcanpassyourownmemorycacheimplementation/你可以通过自己的内存缓存实现
				.memoryCache(new WeakMemoryCache())
				.memoryCacheSize(2 * 1024 * 1024)
				.diskCacheSize(80 * 1024 * 1024)
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				// 将保存的时候的URI名称用MD5加密
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.discCacheFileCount(100)
				// 缓存的文件数量
				.diskCache(new UnlimitedDiskCache(cacheDir))
				// 自定义缓存路劲
				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.imageDownloader(
						new BaseImageDownloader(context, 5 * 1000, 30 * 1000))// connectTimeout(5s),readTimeout(30)超时时间
				.writeDebugLogs()// Removeforreleaseapp
				.build();// 开始构建
		ImageLoader.getInstance().init(configuration);

		if (FileHelper.isFileExist(path)) {
			Bitmap bmp = null;
			try {
				Util util = new Util(context);
				bmp = util.getPathBitmap(Uri.fromFile(new File(path)),
						(int) (context.getResources()
								.getDimension(R.dimen.dimen_120)),
						(int) (context.getResources()
								.getDimension(R.dimen.dimen_70)));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			if (bmp == null)
				bmp = BitmapFactory.decodeResource(context.getResources(),
						faliedRID);
			view.setImageBitmap(bmp);
		} else if (TextUtil.isEmpty(url)) {
			Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
					faliedRID);
			view.setImageBitmap(bmp);
		} else {
			imageLoader.init(ImageLoaderConfiguration.createDefault(context));
			imageLoader.displayImage(url, view, options,
					new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							Bitmap bmp = BitmapFactory.decodeResource(
									context.getResources(), startRID);
							((ImageView) view).setImageBitmap(bmp);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								if (bmp != null) {
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							if (loadedImage != null) {
								// loadedImage =
								// ImageUtil.ImageCrop(loadedImage);
								// loadedImage =
								// ImageUtil.zoomBitmap(loadedImage,
								// 200, 200);
								((ImageView) view).setImageBitmap(loadedImage);
							}
						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								if (bmp != null) {
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}
					});
		}
	}

	public static void load(final Context context, ImageView view, String url,
			final int startRID, final int faliedRID) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisc(true).build();
		ImageLoader imageLoader = ImageLoader.getInstance();

		if (TextUtil.isEmpty(url)) {
			Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
					faliedRID);
			bmp = ImageUtil.getRoundedCornerBitmap(bmp,
					UIUtil.px2dip(context, 100));
			view.setImageBitmap(bmp);
		} else {
			imageLoader.init(ImageLoaderConfiguration.createDefault(context));
			imageLoader.displayImage(url, view, options,
					new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							Bitmap bmp = BitmapFactory.decodeResource(
									context.getResources(), startRID);
							bmp = ImageUtil.getRoundedCornerBitmap(bmp,
									UIUtil.dip2px(context, 100));
							((ImageView) view).setImageBitmap(bmp);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							Bitmap bmp = BitmapFactory.decodeResource(
									context.getResources(), faliedRID);
							bmp = ImageUtil.getRoundedCornerBitmap(bmp,
									UIUtil.dip2px(context, 100));
							((ImageView) view).setImageBitmap(bmp);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							if (loadedImage != null) {
								loadedImage = ImageUtil.ImageCrop(loadedImage);
								loadedImage = ImageUtil.zoomBitmap(loadedImage,
										200, 200);
								loadedImage = ImageUtil.getRoundedCornerBitmap(
										loadedImage,
										UIUtil.dip2px(context, 100));
								((ImageView) view).setImageBitmap(loadedImage);
							}
						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
							if (faliedRID > 0) {
								Bitmap bmp = BitmapFactory.decodeResource(
										context.getResources(), faliedRID);
								bmp = ImageUtil.getRoundedCornerBitmap(bmp,
										UIUtil.dip2px(context, 100));
								if (bmp != null) {
									bmp = ImageUtil.getRoundedCornerBitmap(bmp,
											UIUtil.dip2px(context, 100));
									if (view != null) {
										if (view instanceof ImageView) {
											((ImageView) view)
													.setImageBitmap(bmp);
										} else {
											view.setBackgroundDrawable(new BitmapDrawable(
													bmp));
										}
									}
								}
							}
						}
					});
		}
	}
}
